import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

public class Solution207 {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        int[] first=new int[numCourses];
        int[] du=new int[numCourses];
        int[] next=new int[prerequisites.length];
        int[] go=new int[prerequisites.length];
        Arrays.fill(first,-1);
        for (int i=0;i<prerequisites.length;i++){
            next[i]=first[prerequisites[i][0]];
            first[prerequisites[i][0]]=i;
            go[i]=prerequisites[i][1];
            du[go[i]]++;
        }
        int count=0;
        Queue<Integer> queue=new LinkedList<>();
        for (int i=0;i<numCourses;i++){
            if (du[i]==0){
                queue.offer(i);
                count++;
            }
        }
        while (!queue.isEmpty()){
            int t=queue.poll();
            int p=first[t];
            while (p!=-1){
                du[go[p]]--;
                if (du[go[p]]==0){
                    queue.offer(go[p]);
                    count++;
                }
                p=next[p];
            }
        }
        return count==numCourses;
    }

    public static void main(String[] args) {
        System.out.println(new Solution207().canFinish(2,new int[][]{{1,0}}));
    }
}
